package com.justdoit.facedemo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.arcsoft.face.FaceFeature;
import com.arcsoft.face.FaceInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.justdoit.facedemo.base.Result;
import com.justdoit.facedemo.base.Results;
import com.justdoit.facedemo.domain.User;
import com.justdoit.facedemo.mapper.UserMapper;
import com.justdoit.facedemo.service.UserService;
import com.justdoit.facedemo.utils.ArcFaceUtils;
import com.justdoit.facedemo.utils.ArcFaceWorker;
import com.justdoit.facedemo.utils.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    //注入UserService
    private final UserService userService;

    // redis
    private final StringRedisTemplate redisTemplate;

    public UserController(UserService userService, StringRedisTemplate redisTemplate) {
        this.userService = userService;
        this.redisTemplate = redisTemplate;
    }

    //新增和修改
    @PostMapping("/insertOrUpdate")
    public boolean saveUserOrUpdate(@RequestBody User user) {
        return userService.saveUser(user);
    }

    //根据Id删除用户信息
    @DeleteMapping("/{Id}")
    public boolean deleteById(@PathVariable Integer Id) {
        // 删除缓存中的人脸
        redisTemplate.opsForHash().delete("faceTable", String.valueOf(Id));

        //调用mybatis plus的通过id删除的方法实现删除
        return userService.removeById(Id);
    }


    //根据Id批量删除用户信息
    @PostMapping("del/batch")
    public boolean batchDeleteById(@RequestBody List<Integer> Ids) {
        //调用mybatis plus的通过id删除的方法实现删除
        return userService.removeBatchByIds(Ids);
    }

    //查询所有数据 导出为excel
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //查出所有的数据
        List<User> list = userService.list();
        //调用工具类
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("userId", "用户ID");
        writer.addHeaderAlias("userName", "用户名");
        writer.addHeaderAlias("userJob", "工作");
        writer.addHeaderAlias("userIsAdmin", "是否管理");
        writer.addHeaderAlias("userSex", "性别");
        writer.addHeaderAlias("userNumber", "身份证");
        writer.addHeaderAlias("userPhone", "号码");
        writer.addHeaderAlias("userPassword", "用户密码");
        writer.addHeaderAlias("userAccount", "账户");
        writer.addHeaderAlias("userQq", "QQ号");
        writer.addHeaderAlias("userFaceFeature", "人脸信息");
        writer.addHeaderAlias("userAvatarAddress", "头像地址");
        //写出到excel 使用默认样式,强制输出标题
        writer.write(list, true);
        //设置浏览器的响应格式
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("用户信息表-" + DateUtil.today() + ".xls", "utf-8"));
        //输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();

    }

    //mybatis plus分页查询
    @GetMapping("/findPage")
    public IPage<User> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String user_name,//如果前端没有传值就默认为空
                                @RequestParam(defaultValue = "") String user_phone,
                                @RequestParam(defaultValue = "") String user_job) {
        //page对象
        IPage<User> page = new Page<>(pageNum, pageSize);
        //模糊查询拼接
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //判断非空情况
        if (!"".equals(user_name)) {
            queryWrapper.like("user_name", user_name);
        }
        if (!"".equals(user_phone)) {
            queryWrapper.like("user_phone", user_phone);
        }
        if (!"".equals(user_job)) {
            queryWrapper.like("user_job", user_job);
        }

        IPage<User> userPage = userService.page(page, queryWrapper);
        return userPage;
    }

    /**
     * 添加人脸接口
     *
     * @param map   64编码后的图片数据
     * @return 返回保存结果
     */
    @PostMapping("/addFace")
    public Result<Object> addFace(@RequestBody Map <String,String>map) {
        String file = map.get("userFaceFeature");
        if (!file.isEmpty()) {
            final User user = new User();
            try {
                user.setUserId(Integer.parseInt(map.get("userId")));
                user.setUserName(map.get("userName"));
                user.setUserJob(map.get("userJob"));
                user.setUserSex(map.get("userSex"));
                user.setUserNumber(map.get("userNumber"));
                user.setUserPhone(map.get("userPhone"));
                user.setUserQq(map.get("userQQ"));
                user.setUserFaceFeature(new BASE64Decoder().decodeBuffer(file.substring(file.indexOf(",")+1)));
            } catch (IOException e) {
                e.printStackTrace();
            }

            return userService.UserFace(user);
        }
        return Results.newError("图片或用户id为空");
    }

    /**
     *  1 : N 人脸对比接口
     * @param file 人脸64编码数据
     * @return 对比成功后的用户信息，失败为null
     */
    @PostMapping("/selectFace")
    public Result<User> selectFace(@RequestBody String file){
        if (!file.isEmpty()) {

            try {
                // 传入解码后的图片
                return userService.selectFace(new BASE64Decoder().decodeBuffer(file.substring(file.indexOf(",")+1)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Results.newError("上传的图片为空");
    }


    @PostMapping("/login")
    public Result<Object> Login(@RequestBody Map<String,String> map){
       return userService.login(map.get("username"),map.get("password"));
    }

    @PostMapping("/register")
    public Result<Object> Register(@RequestBody Map<String,String> map){
        return userService.register(map.get("username"),map.get("password"));
    }

}
